package personnal.blogprinter;

import java.util.Collection;
import java.util.EmptyStackException;

import org.apache.log4j.Logger;

import personnal.blogprinter.data.PostError;
import personnal.blogprinter.data.PostInfo;
import personnal.blogprinter.data.PostRange;
import personnal.blogprinter.exceptions.GenerationException;
import personnal.blogprinter.generator.Generator;
import personnal.blogprinter.generator.HtmlPdfGenerator;

import com.lowagie.text.ExceptionConverter;

public class BlogPostHandler {

    private static Logger logger = Logger.getLogger(BlogPostHandler.class);

    protected WordpressClient client;
    protected Collection<PostError> errorQueue;

    private Generator generator;

    public BlogPostHandler(WordpressClient client, Collection<PostError> errorQueue) {
        super();
        this.client = client;
        this.errorQueue = errorQueue;
        this.generator = createGenerator();
    }

    public void handlePostRange(PostRange postRange) {
        logger.info("Handling next PostRange");
        try {
            logger.info("Creating pdf generator");
            // Generator generator = createGenerator(postRange);
            this.generator.init(postRange.getTargetFile());
            for (PostInfo postId : postRange.getPostIds()) {
                logger.info("Handling post with id=" + postId.getId());
                handlePost(this.generator, postId);
            }
            this.generator.destroy();
        } catch (GenerationException e) {
            logger.error("Can't create PDF Generator", e);
        } catch (ExceptionConverter e) {
            logger.error("Problem while closing pdf document", e);
        }
    }

    protected void handlePost(Generator generator, PostInfo postId) {
        PostInfo postInfo = null;
        try {
            postInfo = this.client.getPostById(postId.getId());
            logger.info("Adding post content (postId=" + postId + ", postTitle=" + postInfo.getTitle() + ")");
            generator.addPost(postInfo);
        } catch (EmptyStackException e) {
            this.errorQueue.add(new PostError(postId.getId(), e));
            logger.error("Can't handle post with id=" + postId.getId());// , e);
        } catch (Exception e) {
            this.errorQueue.add(new PostError(postId.getId(), e));
            logger.error("Can't handle post with id=" + postId.getId());// , e);
        }
    }

    protected Generator createGenerator() {
        // return new PdfGenerator();
        return new HtmlPdfGenerator();
        // return new TestGenerator();
    }

}
